/*
 * NetClient.cpp
 *
 *  Created on: 1 mar 2010
 *      Author: Lunkan
 */

#include "Client.h"

Client::Client(string ip, int port) {

	/* Open a listening socket */
	if (!(recv_socket = SDLNet_UDP_Open(port))) {
		cout<<"Receive Socket Error: "<<SDLNet_GetError()<<endl;
	}
	/* Open a sending socket */
	if (!(send_socket = SDLNet_UDP_Open(0))) {
		cout<<"Send Socket Error: "<<SDLNet_GetError()<<endl;
	}

	if (SDLNet_ResolveHost(&host, ip.c_str(), port) == -1)
	{
		cout<<"SDLNet_ResolveHost: "<<SDLNet_GetError()<<endl;
	}

	recv_packet = SDLNet_AllocPacket(512);
	send_packet = SDLNet_AllocPacket(512);
	send_packet->address.host = host.host;
	send_packet->address.port = host.port;

	accepted = false;

	cout << "Client succesfully loaded." << endl;
}

Client::~Client() {
	SDLNet_FreePacket(recv_packet);
	SDLNet_FreePacket(send_packet);
	SDLNet_Quit();
}

void Client::send(string mess) {
	//cout << "Send" << endl;
	const char *m;
	m = mess.c_str();

	send_packet->data = (Uint8*)m;
	send_packet->len = strlen((char *)send_packet->data) + 1;

	SDLNet_UDP_Send(recv_socket, -1, send_packet);
	//cout << "Sent." << endl;

}

string Client::receive() {
	//cout << "Receive" << endl;

	if (SDLNet_UDP_Recv(recv_socket, recv_packet) != 0) {
		string ret;

		ret = string( (char *)recv_packet->data );
		cout<<"Received:    "<< ret << endl;

		// Accepted
		if (ret == "1") {
			accepted = true;
		}
		return ret;
	}

	return "";

}



